class WebSocketClass {
    constructor() {
        this.url = 'wss://amojito.cn:8000'
        this.lists = new Map() //存放不同类型信息的 type fn 对
        this.connect()
    }

    //连接开启ws
    connect() {
        this.ws = new WebSocket(this.url)
        this.ws.onopen = e => {
            console.log('连接ws成功！')
            // this.ws.send('success')
        }
        //获取ws发来的消息
        this.ws.onmessage = e => {
            console.log(e.data)
            this.emit('count', e.data)
        }
        //监听关闭
        this.ws.onclose = e => {
            console.log('ws关闭！')
            this.connect()
        }
    }

    //订阅消息
    on(type, fn) {
        if (!this.lists.get(type)) {
            this.lists.set(type, [])
        }

        this.lists.get(type).push(fn)
    }

    //发布消息
    emit(type, ...args) {
        const arr = this.lists.get(type);
        arr && arr.forEach(fn => {
            fn.apply(null, args)
        })
    }
    

    //关闭ws连接
    close() {
        console.log('ws连接关闭')
        this.ws.close()
    }
}

export default new WebSocketClass()